package com.wang.project.consumer.integral;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.wang.project.model.entity.IntegralOrder;
import com.wang.project.model.entity.InterfaceInfo;
import com.wang.project.model.modle.MQIntegralModel;
import com.wang.project.service.IntegralOrderService;
import com.wang.project.service.InterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@RocketMQMessageListener(
        topic = "integral_interface_topic",
        consumerGroup = "payment-integral-group"
)
public class orderIntegralInterfaceConsumer implements RocketMQListener<MQIntegralModel> {
    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private IntegralOrderService integralOrderService;

    /**
     * 创建积分兑换接口的订单
     *
     * @param mqIntegralModel
     */
    @Override
    public void onMessage(MQIntegralModel mqIntegralModel) {
        log.info("orderIntegralInterfaceConsumer mqIntegralModel:{}", JSONUtil.toJsonStr(mqIntegralModel));
        IntegralOrder integralOrder = this.convertModel(mqIntegralModel);
        boolean result = integralOrderService.save(integralOrder);
        if (!result) {
            log.info("orderIntegralInterfaceConsumer save IntegralOrder err");
        }
        log.info("orderIntegralInterfaceConsumer save IntegralOrder success");
    }

    /**
     * 组装参数
     *
     * @param mqIntegralModel
     * @return
     */
    public IntegralOrder convertModel(MQIntegralModel mqIntegralModel) {
        IntegralOrder integralOrder = new IntegralOrder();
        integralOrder.setUserId(mqIntegralModel.getUserId());
        integralOrder.setExpendIntegralAmount(mqIntegralModel.getExpendIntegralAmount());
        integralOrder.setExchangeType(mqIntegralModel.getExchangeType());
        //生成订单编号
        final String orderNumPrefix = "II";
        String orderCode = orderNumPrefix + IdUtil.simpleUUID();
        //生成 exchangeProductName 商品名称
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(mqIntegralModel.getInterfaceId());
        String exchangeProductName = interfaceInfo.getName();
        integralOrder.setOrderCode(orderCode);
        integralOrder.setExchangeProductName(exchangeProductName);
        log.info("orderIntegralInterfaceConsumer integralOrder:{}", JSONUtil.toJsonStr(integralOrder));
        return integralOrder;
    }
}
